<template>
  <div class="building-add-wrapper">
    <div class="top">
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="top"
      >
        <div class="title">房屋基本信息</div>
        <el-row :gutter="100">
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="产权单位" prop="propertyOwner">
              <el-select
                class="data-input"
                v-model="form.propertyOwner"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['propertyUnit']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="不动产权证号" prop="certificate">
              <el-input
                class="data-input"
                v-model="form.certificate"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="房屋名称" prop="name">
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="所在园区" prop="parkId">
              <el-select
                class="data-input"
                v-model="form.parkId"
                placeholder="请选择"
                @change="handleChangeParkId"
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="详细地址" prop="address">
              <el-input
                class="data-input"
                v-model="form.address"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="经纬度" prop="position">
              <el-input
                class="data-input1"
                v-model="form.position"
                placeholder="请输入"
              ></el-input>
              <el-button
                type="primary"
                @click="chooseLocationDialogVisible = true"
                >定位</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="建成年份" prop="year">
              <el-date-picker
                class="data-input"
                v-model="form.year"
                type="year"
                value-format="YYYY"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="房屋类型" prop="houseType">
              <el-select
                class="data-input"
                v-model="form.houseType"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['buildingType']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="房屋结构" prop="structure">
              <el-select
                class="data-input"
                v-model="form.structure"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['buildingStructure']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="建筑高度(m)" prop="height">
              <el-input
                class="data-input"
                v-model="form.height"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="建筑总层数" prop="floors">
              <el-input
                class="data-input"
                v-model="form.floors"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="地下层数" prop="undergroundFloors">
              <el-input
                class="data-input"
                v-model="form.undergroundFloors"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="证载用途" prop="usage">
              <el-input
                class="data-input"
                v-model="form.usage"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="证载面积(m²)" prop="certificateArea">
              <el-input
                class="data-input"
                v-model="form.certificateArea"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="实际面积(m²)" prop="actualArea">
              <el-input
                class="data-input"
                v-model="form.actualArea"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="使用情况" prop="useStatus">
              <el-select
                class="data-input"
                v-model="form.useStatus"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['buildingUsage']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="实物状况" prop="houseStatus">
              <el-select
                class="data-input"
                v-model="form.houseStatus"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of dict['buildingStatus']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="是否为危房" prop="dangerHouse">
              <el-radio-group
                v-model="form.dangerHouse"
                @change="handleChangeDangerHouse"
              >
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="危房等级" prop="dangerLevel">
              <el-select
                class="data-input"
                v-model="form.dangerLevel"
                placeholder="请选择"
                :disabled="form.dangerHouse === '0'"
              >
                <el-option
                  v-for="(item, index) of dict['buildingLevel']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="是否为重点区域" prop="keyArea">
              <el-radio-group v-model="form.keyArea">
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="12" :lg="12" :xl="8">
            <el-form-item label="入驻企业数">
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
                readonly
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :md="24" :lg="24" :xl="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                class="data-input-area"
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="24" :xl="24">
            <el-form-item label="房屋范围">
              <VUpload
                :isPlain="true"
                :limit="1"
                uploadText="上传（geojson格式）"
                v-model="form.geojsonFile"
                width="250"
              />
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="24" :xl="24">
            <el-form-item label="房屋照片">
              <VUpload
                listType="picture-card"
                accept=".png, .jpg, .jepg"
                v-model="form.imgs"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          房屋所在土地信息
          <el-button type="primary" @click="handleAddLand">关联土地</el-button>
        </div>
        <el-table
          class="custom-table"
          :data="form.mapRegion.pkid ? [form.mapRegion] : []"
        >
          <el-table-column prop="propertyOwner" label="产权人">
            <template #default="scope">
              {{
                getDictValue('propertyUnit', scope.row.propertyOwner)
              }}</template
            >
          </el-table-column>
          <el-table-column prop="certificate" label="土地产权证号" />
          <el-table-column prop="name" label="宗地名称" />
          <el-table-column prop="area" label="土地面积(m²)" />
          <el-table-column prop="character" label="土地性质">
            <template #default="scope"
              >{{ getDictValue('landNature', scope.row.character) }}
            </template>
          </el-table-column>
          <el-table-column prop="usage" label="土地用途">
            <template #default="scope">
              {{ getDictValue('landUse', scope.row.usage) }}</template
            >
          </el-table-column>
          <el-table-column prop="useStatus" label="使用情况">
            <template #default="scope">
              {{ getDictValue('landUsage', scope.row.useStatus) }}</template
            >
          </el-table-column>
          <el-table-column prop="useYear" label="使用年限" />
          <el-table-column prop="remark" label="备注" width="300">
            <template #default="scope">
              <el-form-item class="table-form-item" label="">
                <el-input
                  v-model="form.regionRemark"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" link @click="handleRemoveLand(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="title">
          承租信息
          <el-button type="primary" @click="handleAddTenant"
            >关联承租方</el-button
          >
        </div>
        <el-table class="custom-table" :data="form.renterList">
          <el-table-column prop="floor" label="楼层">
            <template #default="scope"> {{ scope.row.floor }}F </template>
          </el-table-column>
          <el-table-column prop="type" label="承租方类型">
            <template #default="scope">
              {{ getDictValue('tenantType', scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="承租方名称" />
          <el-table-column prop="code" label="承租方代码" />
          <el-table-column prop="businessScope" label="经营范围" />
          <el-table-column prop="houseRenterRemark" label="备注" width="300">
            <template #default="scope">
              <el-form-item class="table-form-item" label="">
                <el-input
                  v-model="scope.row.houseRenterRemark"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" link @click="handleRemoveTenant(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="bottom">
      <el-button @click="handleClose" :loading="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"
        >保存</el-button
      >
    </div>
    <LandChooseDialog
      ref="landChooseDialogRef"
      :parkId="form.parkId"
      v-model="form.mapRegion"
    />
    <TenantChooseDialog
      ref="tenantChooseDialogRef"
      :parkId="form.parkId"
      :floorsOptions="floorsOptions"
      @change="handleAddTenantData"
    />
    <ChooseLocation
      v-model:dialog-visible="chooseLocationDialogVisible"
      :latlnt="form.position"
      @submitLocation="handleChooseLocation"
    />
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ChooseLocation from '@/components/chooseLocation.vue'
import VUpload from '@/components/upload/index.vue'
import LandChooseDialog from './components/landChooseDialog.vue'
import TenantChooseDialog from './components/tenantChooseDialog.vue'
import { CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import {
  buildingAdd,
  buildingUpdate,
  buildingDetail,
} from '@/api/manager/dataManage/building'
import { parkPageList } from '@/api/manager/dataManage/park'
import { useDict } from '@/hooks/useDict'
const { dict, getDictValue } = useDict([
  'propertyUnit',
  'buildingType',
  'yn',
  'buildingStatus',
  'buildingType',
  'buildingStructure',
  'buildingLevel',
  'landNature',
  'landUse',
  'landUsage',
  'tenantType',
  'buildingUsage',
])
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const handleDetail = async () => {
  const res = await buildingDetail({ pkid: route.query.pkid })
  if (res.success) {
    // 处理园区范围文件
    if (res.data.geoJsonFile) {
      res.data.geojsonFile = [res.data.geoJsonFile]
    } else {
      res.data.geojsonFile = []
    }
    delete res.data.geoJsonFile
    // 处理附件资料
    res.data.imgs = res.data.imgList || []
    delete res.data.imgList
    // 处理关联土地
    res.data.mapRegion = res.data.mapRegion || {}
    form.value = { ...res.data }
    // 处理承租方
    res.data.renterList.forEach((item) => {
      item.renterId = item.pkid
    })
  } else {
    ElMessage.error(res.message)
  }
}
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}
const dialogVisible = ref(false)
const handleClose = () => {
  router.push({ name: 'building' })
}
const formRef = ref(null)
const form = ref({
  dangerHouse: '0',
  keyArea: '0',
  mapRegion: {},
  renterList: [],
})
const rules = ref({
  parkId: [{ required: true, message: '请选择所在园区', trigger: 'blur' }],
  certificate: [
    { required: true, message: '请输入不动产权证号', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入房屋名称', trigger: 'blur' }],
  floors: [
    { required: true, message: '请输入房屋总层数', trigger: 'blur' },
    {
      pattern: /^[1-9]\d*$/,
      message: '请输入正整数',
      trigger: 'blur',
    },
  ],
  undergroundFloors: [
    { required: true, message: '请输入地下层数', trigger: 'blur' },
    {
      pattern: /^[+]{0,1}(\d+)$/,
      message: '请输入正整数',
      trigger: 'blur',
    },
  ],
  certificateArea: [
    { required: true, message: '请输入证载面积', trigger: 'blur' },
    {
      pattern: /^(?!0$)\d*(\.\d{1,2})?$/,
      message: '请输入带0-2位小数的正确数字',
      trigger: 'blur',
    },
  ],
  actualArea: [
    { required: true, message: '请输入实际面积', trigger: 'blur' },
    {
      pattern: /^(?!0$)\d*(\.\d{1,2})?$/,
      message: '请输入带0-2位小数的正确数字',
      trigger: 'blur',
    },
  ],
  // name: [{ required: true, message: '请选择使用情况', trigger: 'blur' }],
  keyArea: [
    { required: true, message: '请选择是否为重点区域', trigger: 'blur' },
  ],
})
const handleChangeDangerHouse = () => {
  form.value.dangerLevel = ''
}
const handleChangeParkId = (val) => {
  form.value.mapRegion = {}
  form.value.regionRemark = ''
  form.value.renterList = []
}
const landChooseDialogRef = ref()
const handleAddLand = () => {
  if (!form.value.parkId) {
    ElMessage.warning('请先选择所属园区')
    return
  }
  landChooseDialogRef.value.dialogVisible = true
}
const handleRemoveLand = () => {
  form.value.mapRegion = {}
  form.value.regionRemark = ''
}
const tenantChooseDialogRef = ref()
const floorsOptions = ref([])
const handleAddTenant = () => {
  if (!form.value.parkId) {
    ElMessage.warning('请先选择所属园区')
    return
  }
  if (!form.value.floors) {
    ElMessage.warning('请先输入建筑总层数')
    return
  }
  floorsOptions.value = []
  if (form.value.undergroundFloors) {
    for (let i = 1; i <= Number(form.value.undergroundFloors); ++i) {
      floorsOptions.value.push({ name: -i + 'F', value: -i })
    }
    for (
      let i = 1;
      i <= Number(form.value.floors) - Number(form.value.undergroundFloors);
      ++i
    ) {
      floorsOptions.value.push({ name: i + 'F', value: i })
    }
  }
  tenantChooseDialogRef.value.dialogVisible = true
}
const handleAddTenantData = (data) => {
  data.forEach((item) => {
    item.renterId = item.pkid
    item.pkid = ''
  })
  form.value.renterList = form.value.renterList.concat(data)
  console.log('form.value.renterList', form.value.renterList)
}
const handleRemoveTenant = (scope) => {
  form.value.renterList.splice(scope.$index, 1)
}
const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理房屋范围文件
      if (params.geojsonFile && params.geojsonFile.length > 0) {
        params.geojsonFileId = params.geojsonFile.map((i) => i.pkid).join(',')
      } else {
        params.geojsonFileId = ''
      }
      delete params.geojsonFile
      // 处理附件资料
      if (params.imgs && params.imgs.length > 0) {
        params.imgs = params.imgs
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.imgs = ''
      }
      // 处理关联土地
      params.regionId = params.mapRegion.pkid || ''
      delete params.mapRegion
      // 处理承租方
      const renterList = []
      params.renterList.forEach((item) => {
        renterList.push({
          pkid: item.pkid,
          renterId: item.renterId,
          floor: item.floor,
          houseRenterRemark: item.houseRenterRemark,
        })
      })
      params.renterList = renterList

      try {
        let res
        if (form.value.pkid) {
          res = await buildingUpdate(params)
        } else {
          res = await buildingAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          router.push({ name: 'building' })
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const chooseLocationDialogVisible = ref(false)
const handleChooseLocation = (val) => {
  form.value.position = val.longitude + ',' + val.latitude
  chooseLocationDialogVisible.value = false
}
onMounted(() => {
  initParkList()
  if (route.query.parkId) {
    form.value.parkId = route.query.parkId
  }
  if (route.query.pkid) {
    handleDetail()
  }
})
</script>
<style lang="scss" scoped>
:deep(.table-form-item) {
  width: 100%;
  margin-bottom: 0px;
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
:deep(.data-input) {
  width: 280px !important;
}
:deep(.data-input1) {
  width: 220px !important;
}
:deep(.data-input-area) {
  width: calc(100% - 180px) !important;
}
.custom-table {
  margin-bottom: 45px;
}
.building-add-wrapper {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0px 0px 10px 0px rgba(72, 121, 238, 0.1);
  box-sizing: border-box;
  padding-top: 20px;

  .top {
    width: 100%;
    height: calc(100% - 70px);
    box-sizing: border-box;
    padding: 0px 40px 0px 20px;
    overflow-y: auto;
  }

  .bottom {
    width: 100%;
    height: 70px;
    box-sizing: border-box;
    border-top: 1px solid #d5deed;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.title {
  font-size: 16px;
  line-height: 30px;
  font-weight: 500;
  color: #151515;
  margin-bottom: 20px;
  position: relative;
  padding-left: 10px;

  &::before {
    content: ' ';
    position: absolute;
    left: 0;
    top: 7px;
    width: 4px;
    height: 16px;
    background: linear-gradient(0deg, #4575ee 0%, #6297f5 100%);
    border-radius: 2px;
  }
  .el-button {
    margin-left: 25px;
  }
}
</style>
